// 地址
import {
  openSetting,
  getSetting
} from "./setting"
import {
  showToast
} from "../utils/util"
import {
  request
} from "../request/index"


// 点击打开地图获取地址
export const getLocationAddressSetting = () => {
  //获取授权结果查看是否已授权位置
  return new Promise((resolve, reject) => {
    getSetting().then((res) => {
      if (res["scope.userLocation"] != undefined && !res[
          "scope.userLocation"]) {
        console.log("未授权位置(点击官方授权弹框取消按钮后)")
        openSetting().then((res) => {
          console.log(res)
          if (res["scope.userLocation"]) {
            resolve(chooseLocation())
          } else {
            showToast({
              title: "授权失败,请重新授权",
            })
          }
        })
      } else {
        // console.log('完成授权')
        resolve(chooseLocation())
      }
    })
  })
}

// 打开地图选择位置。
export const chooseLocation = () => {
  return new Promise((resolve, reject) => {
    uni.chooseLocation({
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        console.log(err)
      },
    })
  })
}

// 获取当前的地理位置、速度。当用户离开小程序后，此接口无法调用。开启高精度定位，接口耗时会增加，可指定 highAccuracyExpireTime 作为超时时间。地图相关使用的坐标格式应为 gcj02。
export const getLocation = (options) => {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: options.type || "gcj02", //返回可以用于uni.openLocation的经纬度
      altitude: options.altitude || false,
      geocode: options.geocode || false,
      success: (res) => {
        uni.openLocation({
          latitude: latitude,
          longitude: longitude,
          success: result => {
            result.location = res
            resolve(result)
          }
        });
      },
      fail: (err) => {
        console.log(err)
      },
    })
  })
}

// 使用微信内置地图查看位置  data:经纬度
export const openLocation = (data) => {
  return new Promise((resolve, reject) => {
    uni.openLocation({
      ...data,
    })
  })
}
